import {
  Inject,
  Controller,
  Get,
  Post,
  Query,
  Body,
  Files,
  Fields
} from '@midwayjs/core'
import { TableService } from '../service/examples/table.service.js'
import { WorkflowTemplateService } from '../service/examples/workflowTemplate.service.js'
import { WorkflowDataService } from '../service/examples/workflowData.service.js'
import { UserService } from '../service/user.service.js'
import * as fs from 'fs'
import * as path from 'path'
import { UploadMiddleware } from '@midwayjs/busboy'
import { PORT } from '../config/constants.js'

@Controller('/examples')
export class TestController {
  @Inject()
  tableService: TableService

  @Inject()
  workflowTemplateService: WorkflowTemplateService

  @Inject()
  workflowDataService: WorkflowDataService

  @Inject()
  userService: UserService

  @Post('/insertTables')
  async insertTables(@Body() data: any) {
    return this.tableService.insertMany(data)
  }

  @Post('/deleteTable')
  async deleteTable(@Body() data: any) {
    return this.tableService.deleteOne(data)
  }

  @Get('/findTables')
  async findTables(@Query() query: Record<string, any>) {
    return this.tableService.find(query)
  }

  @Post('/postWorkflowTemplate')
  async postWorkflowTemplate(@Body() data: any) {
    return this.workflowTemplateService.insertMany([data])
  }

  @Get('/getWorkflowTemplates')
  async getWorkflowTemplates() {
    return this.workflowTemplateService.find()
  }
  @Get('/getWorkflowTemplateOne')
  async getWorkflowTemplateOne(@Query('name') name: any) {
    if (!name) return false
    return this.workflowTemplateService.findOne({ name: name })
  }
  @Post('/updateWorkflowTemplate')
  async updateWorkflowTemplateOne(@Body() data: any) {
    return this.workflowTemplateService.updateOne(data)
  }
  @Post('/deleteWorkflowTemplate')
  async deleteWorkflowTemplate(@Body() data: any) {
    return this.workflowTemplateService.deleteOne(data)
  }

  @Post('/postWorkflowData', { middleware: [UploadMiddleware] })
  async postWorkflowData(@Files() files: any, @Fields() fields: any) {
    fields.submitter = JSON.parse(fields.submitter)
    fields.formData = JSON.parse(fields.formData)
    fields.flowData = JSON.parse(fields.flowData)
    if (fields.flowData.at(0)) {
      fields.flowData.at(0).status = '处理中'
      fields.status = fields.flowData.at(0).label + ' 处理中'
    }

    files?.forEach((file: any) => {
      fields.formData[file.originalname] ??= []

      fs.writeFileSync(path.resolve('public', file.originalname), file.buffer)
      fields.formData[file.originalname].push(
        `http://localhost:${PORT}/public/${file.originalname}`
      )
    })

    return this.workflowDataService.insertMany(fields)
  }

  @Get('/getWorkflowDatasBySubmit')
  async getWorkflowDatasBySubmit(@Query('username') username: any) {
    return this.workflowDataService.find({
      'submitter.username': username
    })
  }
  @Get('/getWorkflowDatasByExamine')
  async getWorkflowDatasByExamine(@Query('username') username: any) {
    return this.workflowDataService.find({
      flowData: {
        $elemMatch: { username: username, status: { $ne: '未处理' } }
      }
    })
  }
  @Post('/workflowExamine')
  async workflowExamine(@Body() data: any) {
    const workflowData = await this.workflowDataService.findOne({
      _id: data.flowId
    })
    if (workflowData) {
      const flowData = workflowData.flowData
      const index = flowData.findIndex((v: any) => v.id === data.examineId)
      if (index < flowData.length) {
        flowData[index].status = data.status
        if (data.status === '通过') {
          if (index + 1 < flowData.length) {
            flowData[index + 1].status = '处理中'
            workflowData.status = flowData[index + 1].label + ' 处理中'
          } else workflowData.status = data.status
        }
        if (data.status === '否决') workflowData.status = data.status
      } else workflowData.status = data.status

      return this.workflowDataService.updateOne(workflowData)
    } else return false
  }
}
